package com.tuanzi.loan.web.configuration;

import com.tuanzi.loan.core.vo.IdentityResponse;
import com.tuanzi.loan.web.bean.CurrentUserBean;
import com.tuanzi.loan.web.lazy.LazyDataSessionModel;
import lombok.Getter;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * @Auther: 钟富澎
 * @Date: 2019/9/5
 * @Description: 基于 {@link JSFListingBean}实现且带有“会话”性质的 Bean，注入了{@link CurrentUserBean}充当会话。
 */
public abstract class JSFListingSessionBean<T, K extends IdentityResponse> extends JSFListingBean<T, K> implements InitializingBean, ApplicationContextAware {

    protected CurrentUserBean session;

    @Getter
    protected LazyDataSessionModel<T, K> lazyDataModel;

    /**
     * 该Bean对应的页面
     * @return
     */
    protected abstract String page();

    /**
     * 初始化{@link LazyDataSessionModel}
     */
    protected abstract void initLazyDataModel();

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.session = applicationContext.getBean(CurrentUserBean.class);
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        initLazyDataModel();
        CurrentUserBean.addPageForListModel(page(), this.lazyDataModel.getClass());
        loadSearchParamFromSessionIfNecessary();
    }

    private void loadSearchParamFromSessionIfNecessary() {
        LazyDataSessionModel model = session.getSearchParamInSession(lazyDataModel.getClass());
        if (model != null) {
            lazyDataModel = model;
            $ = lazyDataModel.getSearchRequest();
        }
    }
}
